package com.hy.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hy.config.WechatConfig;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Component
public class WechatUtil {

    @Autowired
    private WechatConfig wechatConfig;
    
    private static final String WECHAT_CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?" +
            "appid={appid}&secret={secret}&js_code={code}";
    
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();
    
    /**
     * 通过code获取openid
     * @param code 微信登录code
     * @return openid
     */
    public String getOpenid(String code) {
        String url = WECHAT_CODE2SESSION_URL
                .replace("{appid}", wechatConfig.getAppid())
                .replace("{secret}", wechatConfig.getSecret())
                .replace("{code}", code);

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求微信接口失败，状态码：" + response.code());
            }

            String responseBody = Objects.requireNonNull(response.body()).string();
            JSONObject jsonObject = JSON.parseObject(responseBody);
            
            // 检查微信接口返回的错误
            if (jsonObject.containsKey("errcode") && jsonObject.getInteger("errcode") != 0) {
                throw new RuntimeException("获取openid失败：" + jsonObject.getString("errmsg"));
            }
            
            return jsonObject.getString("openid");
        } catch (IOException e) {
            throw new RuntimeException("请求微信接口异常", e);
        }
    }
} 